/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package commons.util;

import org.openide.util.NbBundle;

/**
 * @author Susanta Tewari
 */
public class Adders {

    /**
     * @param length the length of the byte arrays to be added
     * @return
     */
    public static ByteAdder createByteAdder(final int length) {

        return new ByteAdder() {

            private int[] sum = new int[length];

            @Override
            public void add(byte[] val) {

                if (length != val.length) {

                    final String msg = NbBundle.getMessage(BinaryDataUtil.class,
                                           "Incorrect_Array_Dimension", val.length);

                    throw new IllegalArgumentException(msg);
                }

                for (int i = 0; i < val.length; i++) {

                    sum[i] += val[i];
                }

            }

            @Override
            public int[] sum() {

                return sum;
            }

            @Override
            public void clear() {

                sum = new int[length];
            }
        };
    }


    /**
     * Interface description
     *
     *
     * @version        Enter version here..., 12/10/09
     * @author         Susanta Tewari    
     */
    public interface ByteAdder {

        /**
         * @param val
         * @throws IllegalArgumentException if the dimension is not correct as defined by the
         * implementation
         */
        void add(byte[] val);


        /**
         * sum of values added
         *
         * @return
         */
        int[] sum();


        /**
         * Resets the adder.
         */
        void clear();
    }
}
